package com.dhcc.countlineusers.listener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.dhcc.countlineusers.entity.OnlineUser;
import com.dhcc.countlineusers.utils.OnlineUserListUtils;

/**
 * @description ：当用户发送请求时，判断该用户是否已加入到在线用户列表中.
 * @date ：2016年11月29日 下午7:08:54
 * @author ：WangYG
 */
public class AddOnlineUserListener implements ServletRequestListener {

    @Override
    public void requestDestroyed(ServletRequestEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    @SuppressWarnings("unchecked")
    public void requestInitialized(ServletRequestEvent servletRequestEvent) {
        HttpServletRequest httpServletRequest = (HttpServletRequest)servletRequestEvent.getServletRequest();
        HttpSession httpSession = httpServletRequest.getSession();
        List<OnlineUser> onlineUserList = (ArrayList<OnlineUser>)httpServletRequest.getServletContext().getAttribute("onlineUserList");
        if(null == onlineUserList){
            onlineUserList = new ArrayList<OnlineUser>();
        }
        Object obj = OnlineUserListUtils.findUserBySessionId(onlineUserList, httpSession.getId());
        if(null == obj){//判断是否是当前在线用户，如果不是则加入到当前在线用户列表中
            OnlineUser user = new OnlineUser();//创建用户并初始化用户信息
            user.setSessionIdStr(httpSession.getId());
            user.setIpStr(httpServletRequest.getRemoteAddr());
            user.setLoginTimeStr(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            onlineUserList.add(user);//加入到在线用户列表中
            httpServletRequest.getServletContext().setAttribute("onlineUserList", onlineUserList);//加入到ServletContext全局对象中
        }
    }

}
